package Controller

import (
	"backend/Dao"
	"backend/Service/dbService"
	"github.com/360EntSecGroup-Skylar/excelize"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strconv"
)

type UserController struct {
}

//
// StudentChangePassword
// @Description: 学生改密码
// @author MaTaoXun 2022-01-15 17:50:48
// @return gin.HandlerFunc
//
func (this UserController) StudentChangePassword(c *gin.Context) {
	userId, _ := c.Get("userId")
	pwd := c.Query("newPwd")
	userIdInt, _ := strconv.Atoi(userId.(string))
	studentModel := &Dao.Student{Model: Dao.Model{ID: uint(userIdInt)}}
	dbService.DbConn.Model(studentModel).Updates(Dao.Student{StuPwd: pwd})
	c.String(200, "changeSuccess")
}

//
// AddStudentByExcel
// @Description: 通过excel添加学生
// @author MaTaoXun 2022-01-15 17:51:00
// @return gin.HandlerFunc
//
func (this UserController) AddStudentByExcel(c *gin.Context) {
	// 单文件
	file, _ := c.FormFile("file")
	log.Println(file.Filename)
	open, _ := file.Open()
	f, _ := excelize.OpenReader(open)

	// Get all the rows in the Sheet1.

	var students []Dao.Student
	rows := f.GetRows("Sheet1")
	student := []Dao.Student{}
	dbService.DbConn.Select("stu_num").Find(&student)
	var set = make(map[interface{}]struct{}, 0)
	for _, d := range student {
		set[d.StuNum] = struct{}{}
	}

	for _, row := range rows {
		_, ok := set[row[0]]
		if !ok {
			students = append(students, Dao.Student{
				Model:    Dao.GetModel(),
				StuName:  row[2],
				StuNum:   row[0],
				StuPwd:   row[3],
				StuClass: row[1],
			})
		} else {
			dbService.DbConn.Model(&Dao.Student{}).Where("stu_num = ?", row[0]).Updates(&Dao.Student{
				StuName:  row[2],
				StuPwd:   row[3],
				StuClass: row[1],
			})
		}

	}
	dbService.DbConn.Create(&students)
	c.JSON(http.StatusOK, "wda")

}

//
// GetStudentPage
// @Description: 分页获取学生
// @author MaTaoXun 2022-01-15 17:51:19
// @return gin.HandlerFunc
//
func (this UserController) GetStudentPage(c *gin.Context) {
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	page, _ := strconv.Atoi(c.Query("page"))
	var count int64
	var data []Dao.Student
	dbService.DbConn.Limit(pageSize).Offset((page - 1) * pageSize).Find(&data)
	dbService.DbConn.Model(&Dao.Student{}).Count(&count)
	c.JSON(200, struct {
		StuList []Dao.Student `json:"stuList"`
		Count   int64         `json:"count"`
	}{
		StuList: data,
		Count:   count,
	})
}

// PageStudentByClass
// @Summary 通过班级分页获取学生
// @Description 通过班级分页获取学生
// @Tags 用户班级相关接口
// @Accept application/json
// @Produce application/json
// @Param tk header string true "token"
// @Param pageSize query string true "分页大小"
// @Param page query string true "页码"
// @Param class query string true "班级名"
// @Security ApiKeyAuth
// @Success 200
// @Router /teacher/PageStudentByClass [get]
func (this UserController) PageStudentByClass(c *gin.Context) {
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	page, _ := strconv.Atoi(c.Query("page"))
	class := c.Query("class")
	var count int64
	var data []Dao.Student
	dbService.DbConn.Limit(pageSize).Where("stu_class = ?", class).Offset((page - 1) * pageSize).Find(&data)
	dbService.DbConn.Model(&Dao.Student{}).Where("stu_class = ?", class).Count(&count)
	c.JSON(200, struct {
		StuList []Dao.Student `json:"stuList"`
		Count   int64         `json:"count"`
	}{
		StuList: data,
		Count:   count,
	})
}

//
// GetExcelModel
// @Description: 获取excel模板
// @author MaTaoXun 2022-01-15 17:51:39
// @return gin.HandlerFunc
//
func (this UserController) GetExcelModel(c *gin.Context) {
	file := excelize.NewFile()
	index := file.NewSheet("Sheet1")
	file.SetCellValue("Sheet1", "A1", "32109193")
	file.SetCellValue("Sheet1", "B1", "2021级专硕二班")
	file.SetCellValue("Sheet1", "C1", "马韬循")
	file.SetCellValue("Sheet1", "D1", "123456")
	file.SetActiveSheet(index)
	Buffer, _ := file.WriteToBuffer()
	c.Header("Content-Type", "application/vnd.ms-excel")
	c.Header("Content-Disposition", "attachment; filename=")
	c.Header("response-type", "blob")
	c.Data(http.StatusOK, "application/vnd.ms-excel", Buffer.Bytes())
}

// GetClassList
// @Summary 获取班级列表
// @Description 获取班级列表
// @Tags 用户班级相关接口
// @Accept application/json
// @Produce application/json
// @Param tk header string false "token"
// @Security ApiKeyAuth
// @Success 200
// @Router /teacher/getClassList [get]
func (this UserController) GetClassList(c *gin.Context) {
	var students []map[string]interface{}
	dbService.DbConn.Model(&Dao.Student{}).Distinct().Pluck("stu_class", &students)
	for _, v := range students {
		v["value"] = v["stu_class"]
		v["label"] = v["stu_class"]
	}
	c.JSON(http.StatusOK, students)
}

//
// GetHomeWorkStuListByClass
// @Description: 获取该班级学生和作业绑定情况
// @author MaTaoXun 2022-01-15 17:53:00
// @return gin.HandlerFunc
//
func (this UserController) GetHomeWorkStuListByClass(c *gin.Context) {
	query := c.Query("classId")
	homeWorkId := c.Query("homeWorkId")
	var students []Dao.Student
	dbService.DbConn.Where(&Dao.Student{StuClass: query}).Find(&students)
	var stuHomeWorks []Dao.StuHomework
	dbService.DbConn.Where("homework_id = ?", homeWorkId).Find(&stuHomeWorks)
	stuSet := make(map[int]struct{})
	for _, v := range stuHomeWorks {
		stuSet[v.StuId] = struct{}{}
	}
	var rs struct {
		StuInfo   []Dao.Student
		CheckList []int
	}
	for i := 0; i < len(students); i++ {
		_, ok := stuSet[int(students[i].Model.ID)]
		if ok {
			rs.CheckList = append(rs.CheckList, i)
		}
	}
	rs.StuInfo = students
	c.JSON(http.StatusOK, rs)
}

// DelStudentById
// @Summary 通过id删除学生
// @Description 通过id删除学生
// @Tags 用户学生相关接口
// @Accept application/json
// @Produce application/json
// @Param tk header string false "token"
// @Param id query string true "学生id"
// @Success 200
// @Router /teacher/DelStudentById [get]
func (this UserController) DelStudentById(c *gin.Context) {
	id := c.Query("id")
	idI, _ := strconv.Atoi(id)
	tx := dbService.DbConn.Delete(&Dao.Student{Model: Dao.Model{ID: uint(idI)}})
	if tx.Error != nil {
		c.JSON(500, "无法删除")
	} else {
		c.JSON(200, "delsuc")
	}

}

// ChangeStuPasswd
// @Summary 更改学生密码
// @Description 更改学生密码
// @Tags 用户学生相关接口
// @Accept application/json
// @Produce application/json
// @Param tk header string false "token"
// @Param id query string false "id"
// @Param pwd query string false "密码"
// @Success 200
// @Router /teacher/ChangeStuPasswd [get]
func (this UserController) ChangeStuPasswd(c *gin.Context) {
	id := c.Query("id")
	idI, _ := strconv.Atoi(id)
	pwd := c.Query("pwd")
	tx := dbService.DbConn.Model(&Dao.Student{Model: Dao.Model{ID: uint(idI)}}).Update("stu_pwd", pwd)
	if tx.Error != nil {
		c.JSON(500, "修改失败")
	} else {
		c.JSON(200, "updatesuc")
	}

}

//
// GetCurriculumStuListByClass
// @Description: 获取该班级学生和课程情况
// @author MaTaoXun 2022-01-15 17:53:37
// @return gin.HandlerFunc
//
func (this UserController) GetCurriculumStuListByClass(c *gin.Context) {
	query := c.Query("classId")
	curriculumId := c.Query("curriculumId")
	var students []Dao.Student
	dbService.DbConn.Where(&Dao.Student{StuClass: query}).Find(&students)
	var studentCurriculums []Dao.StudentCurriculum
	dbService.DbConn.Where("curriculum_id = ?", curriculumId).Find(&studentCurriculums)
	stuSet := make(map[int]struct{})
	for _, v := range studentCurriculums {
		stuSet[v.StuId] = struct{}{}
	}
	var rs struct {
		StuInfo   []Dao.Student
		CheckList []int
	}
	for i := 0; i < len(students); i++ {
		_, ok := stuSet[int(students[i].Model.ID)]
		if ok {
			rs.CheckList = append(rs.CheckList, i)
		}
	}
	rs.StuInfo = students
	c.JSON(http.StatusOK, rs)
}

func (this UserController) GetFileByHomeworkAndStu(c *gin.Context) {

}
